package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file/")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //最终目标：d:/files/2025/02/07/xxx.jpg

        //*********第1步:获取并处理文件名*********
        String filename = file.getOriginalFilename();
        System.out.println("filename:"+filename);

        //获取原始文件名后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        System.out.println("suffix:"+suffix);

        //生成全球唯一的文件名
        filename = UUID.randomUUID() + suffix;

        //*********第2步:处理路径*********
        String dirPath = "d:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //********第3步:创建路径*********
        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }

        //*********第4步:保存图片*********
        String filePath = dirPath + datePath + filename;
        file.transferTo(new File(filePath));


        return JsonResult.ok(filename);

    }
}
